package com.ysbt.usercenter.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysbt.usercenter.common.BaseResponse;
import com.ysbt.usercenter.common.ErrorCode;
import com.ysbt.usercenter.common.ResultUtils;
import com.ysbt.usercenter.exception.BusinessException;
import com.ysbt.usercenter.model.UserLoginRequest;
import com.ysbt.usercenter.model.UserRegisterRequest;
import com.ysbt.usercenter.model.domain.User;
import com.ysbt.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ysbt.usercenter.contant.UserContant.ADMIN_ROLE;
import static com.ysbt.usercenter.contant.UserContant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 用户注册接口
     * @param userRegisterRequest 用户登录请求体（userAccount，userPassword，checkPassword）
     * @return 新添加的用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        long l = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(l);
    };

    /**
     * 用户登录接口
     * @param userLoginRequest 用户登录请求体（userAccount，userPassword）
     * @param request 前端发来的请求
     * @return 返回脱敏后的用户数据
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest , HttpServletRequest request){
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);

    };

    /**
     * 用户注销登录，清空session
     * @param request 前端发来的请求
     * @return 1
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        if(request ==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Integer i = userService.userLoginout(request);
        return ResultUtils.success(i);
    };

    /**
     * 返回当前用户
     * @param request 前端发来的请求
     * @return 返回脱敏后的用户数据
     */
    @GetMapping("/current")
    public BaseResponse<User> current(HttpServletRequest request) {
        User user = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null){
           throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        User currentUser = userService.getById(user.getId());
        User safetyUser = userService.getSafetyUser(currentUser);
        return ResultUtils.success(safetyUser);
    }

    /**
     * 查询用户
     * @param username 用户名
     * @param request 前端发来的请求
     * @return 1
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String username, HttpServletRequest request){
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"仅管理员可查询");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> collect = userList.stream().map(user -> {
            return userService.getSafetyUser(user);
        }).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }

    /**
     * 删除用户
     * @param id 用户
     * @param request
     * @return 前端发来的请求
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> userDelete(@RequestBody long id,HttpServletRequest request){
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"仅管理员可删除用户");
        }
        if (id<0){
            throw new BusinessException(ErrorCode.FAIL_SEARCH,"删除失败");
        }
        Boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 鉴权 false不是管理员，或者用户为空，true为管理员，可以进行管理员的操作
     * @param request 前端发来的请求
     * @return true为管理员  false不为管理员
     */
    private boolean isAdmin(HttpServletRequest request){
        User user = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user ==null || user.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return true;
    }
}
